package com.ucode.springboot.starter.web.config;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import cn.hutool.core.date.DateUtil;

/**
 * 默认的string to date的转化
 * @author: liliang
 * @date: 2019年12月17日 上午11:31:00
 */
@Configuration
public class StringToDateConfig {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;
    
    /**
     * 默认时间转化器
     */
    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
        if ((initializer != null ? initializer.getConversionService() : null) != null) {
            GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }
    
    
    /**
     * 默认的string to date的转化器
     * @author: liliang
     * @date: 2019年12月17日 上午11:33:11
     */
    public static class StringToDateConverter implements Converter<String, Date> {

        @Override
        public Date convert(String value) {
            if (value == null || value.trim().length()==0) {
                return null;
            }
            value = value.trim();
            try {
                if (value.contains("-")) {
                    return DateUtil.parse(value);
                } else if (value.matches("^\\d+$")) {
                    Long lDate = new Long(value);
                    return new Date(lDate);
                }
            } catch (Exception e) {
                if (value.contains("+") && value.length() == 24){
                    SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
                    return sdf.parse(value, new ParsePosition(0));
                }
                throw new RuntimeException(String.format("parser %s to Date fail", value));
            }
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        
    }
}
